package com.producteev4j.model.request;


import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: jcarrey
 * Date: 14/05/11
 * TimeImpl: 17:18
 * To change this template use File | Settings | File Templates.
 */
public class ProducteevParameters {

    private static final String PREFIX = "___index___";
    private static final String API_SIG = "api_sig";

    private Map<String, ProducteevParam> parameters = new HashMap<String, ProducteevParam>();

    public final  void putValue(final String key, final Object value) {
        putValue(key, key, value);
    }

    public final  void putValue(final String mapKey, final String paramName, final Object value) {
        parameters.put(mapKey, new ProducteevParam(paramName, ProducteevParamUtil.toString(value)));
    }

    public final  void putMultivalues(final String key,final  Object[] values) {
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                putValue(key + PREFIX + i, key, values[i]);
            }
        }
    }

    public final  Map<String, ProducteevParam> getParams() {
        return parameters;
    }


    public final  String getFullUrl() {
        StringBuilder buffer = new StringBuilder();

        List<String> keys = new ArrayList<String>();
        keys.addAll(parameters.keySet());
        Collections.sort(keys);


        boolean first = true;
        ProducteevParam multiValueParam;
        for (String key : keys) {

            if (!API_SIG.equals(key)) {

                if (!first) {
                    buffer.append("&");
                } else {
                    first = false;
                }

                multiValueParam = parameters.get(key);
                buffer.append(multiValueParam.getParamName()).append("={").append(key).append("}");
            }
        }

        // Finally the userToken
        if (parameters.get(API_SIG) != null) {
            buffer.append("&").append(API_SIG).append("={").append(API_SIG).append("}");
        }

        return buffer.toString();
    }


    public final  String getSignatureUrl() {
        StringBuilder buffer = new StringBuilder();
        List<String> keys = new ArrayList<String>();
        keys.addAll(parameters.keySet());
        Collections.sort(keys);

        // Secondly parameters
        ProducteevParam parameter;
        for (String key : keys) {
            if (!API_SIG.equals(key)) {
                parameter = parameters.get(key);
                buffer.append(parameter.getParamName()).append(parameter.getValue().toString());
            }
        }
        return buffer.toString();
    }

}
